//
//  HttpRequest.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/8.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HttpRequest.h"
#import "GDataXMLNode.h"


@implementation HttpRequest
@synthesize httpError,showAlert,MessageID;

-(NSString*)BuildXMLRequest:(GDataXMLElement*)authNode
                  channelID:(NSString*)channelID
{
    GDataXMLElement *ActiveUpdate = [GDataXMLNode elementWithName:@"ActiveUpdate"];
    GDataXMLNode *defaultNamespace = [GDataXMLNode attributeWithName:@"xmlns" 
                                                         stringValue:@"http://www.activedeck.com/PowerPoint/"];
    
    GDataXMLElement *Subscribe = [GDataXMLNode elementWithName:@"Subscribe"];
    
    GDataXMLElement *Channel = [GDataXMLNode elementWithName:@"Channel"];
    GDataXMLNode *ID = [GDataXMLNode attributeWithName:@"ID" stringValue:channelID];
    GDataXMLNode *From = [GDataXMLNode attributeWithName:@"From" stringValue:[NSString stringWithFormat:@"%d", MessageID]];
    
    [Channel addChild:ID];
    [Channel addChild:From];
    [Subscribe addChild:Channel];
    [ActiveUpdate addChild:defaultNamespace];
    [ActiveUpdate addChild:authNode];
    [ActiveUpdate addChild:Subscribe];
    
    GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:ActiveUpdate] autorelease];
    NSData	*xData = document.XMLData;
    NSString *postXML = [[[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding]autorelease];
    
    // NSLog(@"PostXML =%@" , postXML);
    
    return postXML;
}


-(NSString*)XML_LongPostRequest:(GDataXMLElement*)authNode
                      urlString:(NSString *)urlString
                      channelID:(NSString *)channelID
{
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *contentType = [NSString stringWithFormat:@"text/xml"];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    NSMutableData *postBody = [NSMutableData data];
    NSString *LongRequest = [self BuildXMLRequest:authNode channelID:channelID];
    [postBody appendData:[LongRequest dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postBody];
    
    NSError *ErrMSG = [[NSError alloc]autorelease];
	//get response
	NSHTTPURLResponse* urlResponse = nil;
	NSData *responseData;
    @try
    {
        responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&ErrMSG];
    }@catch(NSException *ex)
    {
        NSLog(@"LongPostRequestFail:%@", ex);
        return  NULL;
    }
	NSString *result = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]autorelease];
    
    NSLog(@"LongPostRespond:%@", result);
    
	NSLog(@"Response Code: %d", [urlResponse statusCode]);
	
    NSLog(@"Error Code %d",[ErrMSG code]);
    
    if([ErrMSG code] == -1005)
        return NULL;
    
    if([ErrMSG code] == -1009 && showAlert)
    {
        showAlert = true;
        
		return [NSString stringWithFormat:@"%d", [ErrMSG code]];
    }
    
    if([urlResponse statusCode] == 200)
        showAlert = true;
	
	NSString *searchFor = @"Error";
	NSRange range;
	range = [result rangeOfString:searchFor];
    
	if (range.location == NSNotFound)
		return result;
	else
	{
        searchFor = @"Sequence contains no elements";
        range = [result rangeOfString:searchFor];
        if(range.location != NSNotFound)
            return @"NOCONTENT";
        
		[self GetResponseMessage:result];
        return @"Error";
	}
    
}

-(NSString*)XML_PostRequest:(NSString *)xmlMessage
                  urlString:(NSString *)urlString
{
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	NSString *contentType = [NSString stringWithFormat:@"text/xml"];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];	
	
	NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[xmlMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[request setHTTPBody:postBody];
	
	NSError *ErrMSG = [[NSError alloc]autorelease];
	//get response
	NSHTTPURLResponse* urlResponse = nil;
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&ErrMSG];
	NSString *result = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]autorelease];
	
    //NSLog(@"PostRespond:%@", result);
    
	NSLog(@"Response Code: %d", [urlResponse statusCode]);
	
    NSLog(@"Error Code %d",[ErrMSG code]);
    
    if([ErrMSG code] == -1009 && showAlert)
    {
        showAlert = false;
        
		return [NSString stringWithFormat:@"%d", [ErrMSG code]];
    }
    
    
    if([urlResponse statusCode] == 200)
        showAlert = true;
	
	NSString *searchFor = @"Error";
	NSRange range;
	range = [result rangeOfString:searchFor];
    
	if (range.location == NSNotFound)
		return result;
	else
	{
        searchFor = @"Sequence contains no elements";
        range = [result rangeOfString:searchFor];
        if(range.location != NSNotFound)
            return @"NOCONTENT";
        
        searchFor = @"User is blocked";
        range = [result rangeOfString:searchFor];
        if(range.location != NSNotFound)
            return @"BLOCKED";
        
		[self GetResponseMessage:result];
        return @"Error";
	}
    
    
}

-(void)GetResponseMessage:(NSString *)result
{
	@try {
		GDataXMLElement *responseNode = [[GDataXMLElement alloc] initWithXMLString:result error:nil];
		GDataXMLNode *mAttrib = [responseNode attributeForName:@"Message"];
		
        httpError.NilValueForKey = [[NSString alloc] initWithString:[NSString stringWithFormat:@"*** Webserver Return Error MSG: %@",[mAttrib stringValue]]];
        
        [responseNode release];
	}
	@catch (NSException * e) {
		httpError.NilValueForKey = [[NSString alloc] initWithString:[NSString stringWithFormat:@"*** Unable to reach Webserver: %@",[e reason]]];
	}
}



-(NSData*)Image_PostRequest:(NSString *)xmlMessage
                  urlString:(NSString *)urlString
{
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	NSString *contentType = [NSString stringWithFormat:@"text/xml"];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];	
	
	NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[xmlMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[request setHTTPBody:postBody];
	
	//get response
	NSHTTPURLResponse* urlResponse = nil;
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&httpError];
    
	//NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSLog(@"Response Code: %d", [urlResponse statusCode]);
    
    
    if([httpError code] == -1009 && showAlert)
    {
        showAlert = FALSE;
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"Download Not Completed"
								   message:@"Please check if you have proper internet connection and try again."
								  delegate:self 
						 cancelButtonTitle:@"OK" 
						 otherButtonTitles:nil];
		
		[alertMSG show];
        [alertMSG release];
        
		return NULL;
    }
    
    if([urlResponse statusCode] == 200)
        showAlert = true;
    
	
	//UIImage *streamImg = [[UIImage alloc] initWithData:responseData];
	
	//responseData.release;
	//result.release;
	//postBody.release;
    
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache release];
    
    //[[NSURLCache sharedURLCache] removeAllCachedResponses];
    
	return responseData;
}

-(NSData*)Video_PostRequest:(NSString *)xmlMessage
                  urlString:(NSString *)urlString
{
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	NSString *contentType = [NSString stringWithFormat:@"text/xml"];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];	
	
	NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[xmlMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[request setHTTPBody:postBody];
	
	//get response
	NSHTTPURLResponse* urlResponse = nil;
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&httpError];
	//NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSLog(@"Response Code: %d", [urlResponse statusCode]);
    
    
    if([httpError code] == -1009 && showAlert)
    {
        showAlert = FALSE;
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"Download Not Completed"
								   message:@"Please check if you have proper internet connection and try again."
								  delegate:self 
						 cancelButtonTitle:@"OK" 
						 otherButtonTitles:nil];
		
		[alertMSG show];
        [alertMSG release];
        
		return NULL;
    }
    
    if([urlResponse statusCode] == 200)
        showAlert = true;
    
    //responseData.release;
	//result.release;
	//postBody.release;
    
	return responseData;
}

+(NSString*)GetSvcURL{
    return @"https://svc.activedeck.com";
    //    return @"http://beta-activedeck.cloudapp.net";
}



- (void)dealloc {
    
    [super dealloc];
}
@end
